<?php

/*****************************************************************************
 * Copyright (C) 2009 Gwathuirim
 *
 * This is free software; you can redistribute it and/or modify it under the
 * terms of the GNU General Public License as published by the Free Software
 * Foundation; either version 3 of the License, or (at your option) any later
 * version.
 *
 * This is distributed in the hope that it will be useful, but WITHOUT ANY
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE. See the GNU Public License for more details
 *
 * To obtain a copy of the GNU General Public License, please see
 * <http://www.gnu.org.licenses/>
 *****************************************************************************/

require_once('include.config.php');
require_once('include.constants.php');
require_once('include.functions.php');

require_once('class.reportmail.php');
require_once('class.multireportmail.php');
require_once('class.singlereportmail.php');

$postData = file_get_contents('php://input');
$requestObject = json_decode($postData);

if (!isset($_ACCOUNTS[$requestObject->username]))
	die_json(CODE_ADDRESSNOTFOUND, "No recipient address found for '$requestObject->username'!");
	
$recipient = $_ACCOUNTS[$requestObject->username];

//The environmentVars, needed by templates to render content
$environmentVars = new stdClass();
$environmentVars->recipient = $recipient;
foreach ($requestObject as $key => $value) {
	if ($key != "reports")
		$environmentVars->$key = $value;
}

//Send the mails
if (!isset($requestObject->sendAsOneMail) || !$requestObject->sendAsOneMail) {
	$responseObject = new stdClass();
	
	for ($i = count($requestObject->reports) - 1; $i >= 0; $i--) {
		$report = $requestObject->reports[$i];

		$mail = new SingleReportMail($report, $environmentVars);
		
		$reportId = $report->id;
		$responseObject->$reportId = $mail->send($recipient);
	}
	
	echo json_encode($responseObject);
} else {
	$mail = new MultiReportMail($requestObject->reports, $environmentVars);
	
	echo json_encode($mail->send($recipient));
}

?>